package org.example.redis;


import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class redisConfig {
    private RedisPropertie redisPropertie;

    private LettuceConfig lettuceConfig;
    public redisConfig(LettuceConfig lettuceConfig,RedisPropertie redisPropertie){
        this.lettuceConfig=lettuceConfig;
        this.redisPropertie=redisPropertie;
    }

    @Bean
    public LettuceConnectionFactory redisConnection(){
        //线程池配置
        GenericObjectPoolConfig genericObjectPoolConfig =new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(lettuceConfig.getMaxIdle());
        genericObjectPoolConfig.setMinIdle(lettuceConfig.getMinIdle());
        genericObjectPoolConfig.setMaxWait(lettuceConfig.getMaxWait());
        genericObjectPoolConfig.setMaxTotal(lettuceConfig.getMaxActive());

        //redis配置
        RedisStandaloneConfiguration redisStandaloneConfiguration =new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(redisPropertie.getHost());
        redisStandaloneConfiguration.setPort(redisPropertie.getPort());
        redisStandaloneConfiguration.setPassword(redisPropertie.getPassword());
        redisStandaloneConfiguration.setDatabase(redisPropertie.getDatabase());

        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder lettucePoolingClientConfigurationBuilder = LettucePoolingClientConfiguration.builder().poolConfig(genericObjectPoolConfig).commandTimeout(Duration.ofMillis(redisPropertie.getTimeout())).shutdownTimeout(Duration.ofMillis(redisPropertie.getShutdownTimeout()));
        LettuceConnectionFactory lettuceConnectionFactory =new LettuceConnectionFactory(redisStandaloneConfiguration,lettucePoolingClientConfigurationBuilder.build());
        return lettuceConnectionFactory;
    }


    @Bean("redisTemplate")
    public RedisTemplate<String,String> redisTemplate(LettuceConnectionFactory connectionFactory){
        RedisTemplate<String,String> redisTemplate =new RedisTemplate<>();
        //覆写链接工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        //key-value 序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}
